<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <!-- <el-row>
                <el-col>
                    <div class="infoTitle">
                        任务设置
                    </div>
                </el-col>
            </el-row> -->
      <div class="secondaryTitle secondaryTitleTheme mrB30">任务设置</div>
      <div style="text-align: left; margin-bottom: 24px">
        <el-button
          :disabled="isDisabled"
          class="commonBut saveBtn funComBut bzjAddJc"
          @click="editData('person', '')"
        >
          <span class="opetareText">批量设置巡查人员</span>
        </el-button>
        <el-button
          class="commonBut saveBtn funComBut"
          @click="editData('term', '')"
        >
          <span class="opetareText">批量设置完成期限</span>
        </el-button>
      </div>
      <el-table
        :data="resultList"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        style="border: 1px solid #dfe6ec"
        :row-key="recordId"
        ref="multipleTable"
        @selection-change="selectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="50" :reserve-selection="true">
        </el-table-column>
        <el-table-column
          prop="unitName"
          label="巡查项目名称"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="templateName"
          label="巡查模板"
          align="center"
          min-width="200"
        ></el-table-column>
        <!-- <el-table-column prop="jobUserName" label="任务人员" min-width="170" align="center"></el-table-column> -->
        <el-table-column label="任务人员" width="230">
          <template slot-scope="scope">
            <copyText
              :tableIndex="scope.$index"
              :copyTextName="scope.row.jobUserName"
              :columnName="'jobUserName'"
            ></copyText>
          </template>
        </el-table-column>
        <el-table-column
          prop="endDate"
          label="完成期限"
          align="center"
          min-width="120"
        ></el-table-column>
        <el-table-column
          label="操作"
          prop="hasFile"
          min-width="120"
          align="left"
        >
          <template slot-scope="scope">
            <p>
              <el-link
                type="primary"
                @click="editData('edit', scope.row)"
                v-hasBtn="'patrolTaskList:update'"
                >编辑</el-link
              >
              <el-link
                type="primary"
                @click="delData(scope.row.id)"
                v-hasBtn="'patrolTaskList:delete'"
                >删除</el-link
              >
            </p>
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-if="isShow">
          <emptyTable :emptyText="emptyText"></emptyTable>
        </div>
      </el-table>
      <div class="clearfix">
        <el-col :span="24" class="toolbar" style="text-align: right">
          <!-- <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="pageNo"
                    :page-sizes="pageSizes"
                    :page-size="pageSizeNumber"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    ref="pagination"
                ></el-pagination> -->
        </el-col>
      </div>
      <el-row class="btnBox">
        <el-button
          size="medium"
          class="submitBtn commonBut saveBtn"
          v-if="artificialOrRandom == 'random'"
          @click="confirm('again')"
          v-hasBtn="'patrolTaskList:add'"
          :loading="againLoading"
          >再次随机</el-button
        >
        <el-button
          size="medium"
          class="submitBtn commonBut saveBtn"
          @click="goBack()"
          >上一步</el-button
        >
        <el-button
          size="medium"
          class="submitBtn commonBut saveBtn"
          @click="confirm('sure')"
          v-hasBtn="'patrolTaskList:add'"
          :loading="sureLoading"
          >确定创建</el-button
        >
        <el-button size="medium" class="cancelBtn" @click="goList()"
          >取消创建</el-button
        >
      </el-row>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="cancelAccountDialog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-form
        class="el-form1"
        :model="formData"
        ref="formRef"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="任务人员" prop="jobUserIds" v-if="isShowPerson">
          <el-select
            clearable
            filterable
            multiple
            placeholder="请选择"
            class="optionWidth"
            v-model="jobUserIds"
            multiple-limit="20"
            :popper-append-to-body="false"
          >
            <el-option
              v-for="item in personOptions"
              :key="item.id"
              :label="item.nickname + '(' + item.username + ')'"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务期限" prop="endDate" v-if="isShowTerm">
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            placeholder="请选择"
            :picker-options="pickerOptions"
            class="optionWidth"
            value-format="yyyy-MM-dd"
            :append-to-body="false"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="onSave"
          :loading="isSaveLoading"
          class="save"
          v-hasBtn="'patrolTaskList:update'"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'inspectionTaskResult',
  data() {
    return {
      titleText: '创建巡查任务',
      back: true,
      resultList: [],
      emptyText: '暂无数据',
      isShow: false, //列表加载
      artificialOrRandom: '',
      selectData: [],
      dialogVisible: false,
      formData: {
        jobUserIds: [],
        endDate: '',
      },
      rules: {
        jobUserIds: [
          { required: true, message: '请选择人员', trigger: 'blur' },
        ],
        endDate: [
          { required: true, message: '请选择任务期限', trigger: 'blur' },
        ],
      },
      isSaveLoading: false,
      personOptions: [], //人员下拉接口
      taskTermOptions: [],
      isShowTerm: false,
      isShowPerson: false,
      dialogTitle: '',
      selectId: [], //table多选id
      pickerOptions: this.processDate(),
      confirmIds: [],
      jobUserIds: [], //人员数组
      sureLoading: false, //确认创建loading
      againLoading: false,
    }
  },
  watch: {},
  created() {
    this.artificialOrRandom = this.$route.query.type
    this.getXCList()
    this.getPersonData()
  },
  mounted() {},
  methods: {
    goBack() {
      this.$router.push({
        path: '/home/inspectionTask/addInspectionTask',
        name: 'addInspectionTask',
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/patrol/patrolTaskList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    goList() {
      this.$router.push({
        path: '/home/patrol/patrolTaskList',
        name: 'patrolTaskList',
        query: {
          activeName: 'second',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/patrol/patrolTaskList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    handleSizeChange() {},
    handleCurrentChange() {},
    editData(type, row) {
      if (row) {
        this.$refs.multipleTable.setCurrentRow(row)
      }
      if (this.selectData.length == 0 && row == '') {
        this.$message({
          message: '请先选择需要批量设置的任务',
          type: 'warning',
        })
        return
      }
      if (type == 'term') {
        this.dialogTitle = '批量期限设置'
        this.isShowTerm = true
        this.isShowPerson = false
        this.jobUserIds = ''
        this.formData.jobUserIds = ''
        this.formData.endDate = ''
      } else if (type == 'person') {
        this.dialogTitle = '批量人员设置'
        this.isShowPerson = true
        this.isShowTerm = false
        this.jobUserIds = ''
        this.formData.jobUserIds = ''
        this.formData.endDate = ''
      } else {
        this.dialogTitle = '编辑'
        this.isShowPerson = true
        this.isShowTerm = true
        if (row.jobUserIds) {
          this.jobUserIds = row.jobUserIds.split(',')
          this.formData.jobUserIds = row.jobUserIds.split(',')
        } else {
          this.jobUserIds = row.jobUserIds
          this.formData.jobUserIds = row.jobUserIds
        }
        this.formData.endDate = row.endDate
      }
      this.dialogVisible = true
      this.getFormData(type, row)
    },
    delData(id) {
      this.$confirm('确认删除吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.axios({
            method: 'post',
            url: 'api-gov/ipqcjobtemp/expand/delbyid',
            data: {
              id: id,
            },
          })
            .then(
              (response) => {
                if (!response.data.hasError) {
                  this.$message({
                    message: '删除成功',
                    type: 'success',
                  })
                  this.getXCList()
                } else {
                  this.$message({
                    message: '数据获取失败',
                    type: 'error',
                  })
                }
              },
              (response) => {}
            )
            .catch((error) => {})
        })
        .catch(() => {})
    },
    selectionChange(val) {
      this.selectData = val
    },
    cancelAccountDialog() {
      this.dialogVisible = false
      this.$refs.formRef.resetFields()
    },
    // 保存批量和编辑数据
    onSave() {
      this.isSaveLoading = true
      if (this.jobUserIds) {
        this.formData.jobUserIds = this.jobUserIds.join(',')
      }
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.successSave()
        } else {
          this.isSaveLoading = false
          return false
        }
      })
    },
    successSave() {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqcjobtemp/expand/edit',
        data: this.formData,
      })
        .then(
          (response) => {
            this.isSaveLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.cancelAccountDialog()
              this.getXCList()
            } else {
              this.$message({
                message: '数据获取失败',
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    // 获取弹框form表单的值
    getFormData(type, row) {
      this.selectId = []
      this.formData.ids = []
      var ids
      if (row == '') {
        var selectDataLen = this.selectData.length
        for (var i = 0; i < selectDataLen; i++) {
          this.selectId.push(this.selectData[i].id)
        }
        ids = this.selectId.join(',')
        this.formData.ids = ids
      } else {
        this.formData.ids = row.id
      }
    },
    processDate() {
      return {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
      }
    },
    // 批量弹框人员下拉接口
    getPersonData() {
      this.axios({
        method: 'get',
        url: 'api-u/users/usersbyname',
        data: {
          nickName: '',
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.personOptions = response.data.result
            } else {
              this.$message({
                message: '数据获取失败',
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getXCList() {
      this.axios({
        method: 'get',
        url: 'api-gov/ipqcjobtemp/expand/templist',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.resultList = response.data.result.results
            } else {
              this.$message({
                message: '数据获取失败',
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    recordId(row) {
      return row.id
    },
    // 确认创建
    confirm(type) {
      if (type == 'sure') {
        this.sureLoading = true
      } else {
        this.againLoading = true
      }
      var resultListLen = this.resultList.length
      this.confirmIds = []
      for (var i = 0; i < resultListLen; i++) {
        if (type == 'sure') {
          if (
            this.resultList[i].jobUserName == '' ||
            this.resultList[i].endDate == '' ||
            this.resultList[i].jobUserName == null ||
            this.resultList[i].endDate == null
          ) {
            this.$message({
              message: '请填写全部任务的任务人员和完成期限',
              type: 'error',
            })
            this.sureLoading = false
            return
          }
        }
        this.confirmIds.push(this.resultList[i].id)
      }
      this.$nextTick(function () {
        if (type == 'sure') {
          this.confirmSave()
        } else {
          this.againRandom()
        }
      })
    },
    confirmSave() {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqcjob/expand/save',
        data: {
          ids: this.confirmIds.join(','),
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '创建任务成功',
                type: 'success',
              })
              this.sureLoading = false

              this.goList()
            } else {
              this.$message({
                message: '创建任务失败',
                type: 'error',
              })
              this.sureLoading = false
            }
          },
          (response) => {}
        )
        .catch((error) => {
          this.sureLoading = false
        })
    },
    // 再次随机
    againRandom() {
      var formData
      formData = JSON.parse(this.$route.query.formData)
      if (formData.ids) {
        formData.ids = ''
      }
      formData.ids = this.confirmIds.join(',')
      this.axios({
        method: 'post',
        url: 'api-gov/ipqcjobtemp/expand/jobbyrandom',
        data: formData,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '再次随机成功',
                type: 'success',
              })
              this.selectData = []
              this.resultList = []
              this.formData.ids = []
              this.$refs.multipleTable.clearSelection()
              this.getXCList()
            } else {
              this.$message({
                message: '再次随机失败',
                type: 'error',
              })
            }
            this.againLoading = false
          },
          (response) => {}
        )
        .catch((error) => {
          this.againLoading = false
        })
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  .mainCon {
    top: 198px;
    padding: 24px;
    .infoTitle {
      font-size: 16px;
      padding: 16px 24px;
      background: #f5f7fb;
      margin-bottom: 24px;
      color: #333;
      font-weight: 700;
    }
    .proInputWidth {
      width: 65%;
    }
    .btnBox {
      text-align: center;
    }
  }
  .optionWidth {
    width: 310px !important;
  }
}
</style>
